package com.kandinfo.base.admin.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kandinfo.base.admin.constant.WorkGroupDataConstant;
import com.kandinfo.base.admin.domain.UserGroup;
import com.kandinfo.base.admin.domain.WorkGroup;
import com.kandinfo.base.admin.dto.WorkGroupDataDto;
import com.kandinfo.base.admin.dto.WorkGroupPostDto;
import com.kandinfo.base.admin.dto.WorkInputDto;
import com.kandinfo.base.admin.service.AreaService;
import com.kandinfo.base.admin.service.UserGroupService;
import com.kandinfo.base.admin.service.WorkGroupDataService;
import com.kandinfo.base.admin.service.WorkGroupService;
import com.kandinfo.base.common.converter.ConverterService;
import com.kandinfo.base.common.dto.ResultDto;
import com.kandinfo.base.common.dto.ResultDtoFactory;
import com.kandinfo.base.security.SecurityContext;
import com.kandinfo.base.security.annotation.Menu;
import com.kandinfo.base.security.domain.User;
import com.kandinfo.base.security.service.UserService;



/**
 * 
 * Class Name: WorkGroupController Description: WorkGroupController
 * 
 * @author qianqiao
 *
 */
//@Controller
@RequestMapping(value = "/workgroup")
public class WorkGroupController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserGroupService userGroupService;
    @Autowired
    private WorkGroupService workGroupService;
    @Autowired
    private WorkGroupDataService workGroupDataService;
    
    @Autowired
    private AreaService areaService;

    @RequestMapping(value = "", method = RequestMethod.GET)
    @Menu
    public String index(Model model) {
        model.addAttribute("workGroupList", workGroupService.findAll());
        model.addAttribute("userList", userService.findActiveUser());
        model.addAttribute("areaList", areaService.getStoreArea());
        return "/sys/workgroup_list";
    }

    @RequestMapping(value = "/getOrginRefs", method = RequestMethod.GET)
    @ResponseBody
    public ResultDto getRolePermissions(@RequestParam(value = "groupId") Long groupId) {

        List<WorkGroupDataDto> originalPerms = workGroupDataService.findByGroupId(groupId,
                WorkGroupDataConstant.TYPE_QUESTIONSOURCE);
        if (CollectionUtils.isEmpty(originalPerms)) {
            return ResultDtoFactory.toAckNomessage(null);
        } else {
            return ResultDtoFactory.toAckNomessage(originalPerms);
        }
    }

    @RequestMapping(value = "/getOrginUsers", method = RequestMethod.GET)
    @ResponseBody
    public ResultDto getOrginUsers(@RequestParam(value = "groupId") Long groupId) {
        List<User> list = new ArrayList<User>();
        List<UserGroup> originalUsers = userGroupService.findByGroupId(groupId);
        for (UserGroup userGroup : originalUsers) {
            Long userId = userGroup.getUserId();
            User user = userService.findUserById(userId);
            if (user != null) {
                list.add(user);
            }
        }
        return ResultDtoFactory.toAckNomessage("查询成功", list);

    }


    @RequestMapping(value = "/getusers", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto getUsers() {
//         List<User> userList = userService.findActiveUser();
        List<User> userList = userService.getUsersBykey();
        return ResultDtoFactory.toAckNomessage(userList);

    }

    /**
     * 
     * Description: 创建用户做
     *
     * @param createTaskDto
     * @return
     */
    @RequestMapping(value = "/doAdd", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto createTask(@RequestBody WorkInputDto workInputDto) {
        WorkGroup workGroup = ConverterService.convert(workInputDto, WorkGroup.class);
        User loginUser = SecurityContext.getInstance().getCurrentUser();

        if (workGroup.getId() == null) {
            if (!CollectionUtils.isEmpty(workGroupService.checkName(workInputDto.getName()))) {
                return ResultDtoFactory.toNack("用户组名称不能重复！");
            }

            workGroup.setCreateBy(loginUser.getId());
            workGroup.setCreateTs(new Date());
            workGroupService.save(workGroup);
            return ResultDtoFactory.toAck("添加成功");
        } else {
            WorkGroup wg = workGroupService.findOne(workGroup.getId());
            wg.setCreateBy(loginUser.getId());
            wg.setCreateTs(new Date());
            workGroupService.save(wg);
            return ResultDtoFactory.toAck("修改成功");
        }
    }

    // 提交数据
    @RequestMapping(value = "/assignperms", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto assignPermissions(@RequestBody WorkGroupPostDto workGroupPostDto, HttpServletRequest request) {
        Long groupId = Long.parseLong(workGroupPostDto.getWorkGroupId().trim());

        try {
            workGroupDataService.saveWGDatesByGroupId(workGroupPostDto.getRefId(), groupId,
                    WorkGroupDataConstant.TYPE_QUESTIONSOURCE);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDtoFactory.toNack("保存失败");
        }
        return ResultDtoFactory.toAck("保存成功");
    }

    // 提交用户组数据
    @RequestMapping(value = "/assignusers", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto assignUsers(@RequestBody WorkGroupPostDto workGroupPostDto) {
        Long groupId = Long.parseLong(workGroupPostDto.getWorkGroupId().trim());
        String[] userIds = workGroupPostDto.getUserId().split(",");
        int userIdsLength = "".equals(userIds[0]) ? 0 : userIds.length;
        User loginUser = SecurityContext.getInstance().getCurrentUser();
        List<UserGroup> originalUsers = userGroupService.findByGroupId(groupId);
        if (!CollectionUtils.isEmpty(originalUsers)) {
            userGroupService.delete(originalUsers);
        }
        int count = userIdsLength;
        if (userIdsLength > 0) {
            for (int i = 0; i < userIds.length; i++) {
                UserGroup temp = new UserGroup();
                temp.setGroupId(groupId);
                temp.setUserId(Long.valueOf(userIds[i].trim()));
                temp.setCreateTs(new Date());
                temp.setCreateBy(loginUser.getId());

                UserGroup saved = userGroupService.save(temp);
                if (saved != null) {
                    count--;
                }
            }
        }
        if (count == 0) {
            return ResultDtoFactory.toAck("保存成功");
        } else {
            // 回滚数据
            List<UserGroup> nowgroupPerms = userGroupService.findByGroupId(groupId);
            if (!CollectionUtils.isEmpty(nowgroupPerms)) {
                userGroupService.delete(nowgroupPerms);
            }

            for (UserGroup item : originalUsers) {
                UserGroup temp = new UserGroup();
                temp.setId(item.getGroupId());
                temp.setUserId(item.getUserId());
                temp.setCreateTs(item.getCreateTs());
                temp.setCreateBy(item.getCreateBy());
                userGroupService.save(temp);
            }
            return ResultDtoFactory.toNack("保存失败");
        }

    }

    // 提交数据
    @RequestMapping(value = "/assignTextBooks", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto assignTextBooks(@RequestBody WorkGroupPostDto workGroupPostDto, HttpServletRequest request) {
        Long groupId = Long.parseLong(workGroupPostDto.getWorkGroupId().trim());

        try {
            workGroupDataService.saveWGDatesByGroupId(workGroupPostDto.getRefId(), groupId,
                    WorkGroupDataConstant.TYPE_TEXTBOOK);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDtoFactory.toNack("保存失败");
        }
        return ResultDtoFactory.toAck("保存成功");
    }

}
